/*************************************************************************
  > File Name: cam.c
  > Author: Xihany
  > Mail: m1rose@sina.com
  > Created Time: Tue Jul 30 10:50:59 2024
 ************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <linux/videodev2.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>

int main()
{
    // 1、打开视频文件设备
    int camfd = open("/dev/video0", O_RDWR);
    if (camfd < 0)
    {
        perror("open");
        return -1;
    }
    printf("open success, camfd = %d\n", camfd);

    //  2、查询属性、功能
    struct v4l2_capability driver_buf;
    bzero(&driver_buf, sizeof(driver_buf));
    int ret = ioctl(camfd, VIDIOC_QUERYCAP, &driver_buf);
    if (ret < 0)
    {
        perror("ioctl query");
        return -1;
    }
    if (driver_buf.capabilities & V4L2_CAP_VIDEO_CAPTURE)
        printf("support capture\n");

    // 3、枚举出所有的格式，看是否支持要设置的格式
    struct v4l2_fmtdesc fmtdesc;
    fmtdesc.index = 0;
    fmtdesc.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    ioctl(camfd, VIDIOC_ENUM_FMT, &fmtdesc);
    if (fmtdesc.pixelformat & V4L2_PIX_FMT_YUYV)
        printf("support YUYV\n");
    if (fmtdesc.pixelformat & V4L2_PIX_FMT_MJPEG)
        printf("support JPG\n");
    //	fmtdesc.index++;

    // 4、设置格式
    struct v4l2_format fmt;
    fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    fmt.fmt.pix.width = 1280;
    fmt.fmt.pix.height = 720;
    fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_MJPEG;
    ret = ioctl(camfd, VIDIOC_S_FMT, &fmt);
    if (ret < 0)
    {
        perror("ioctl set fmt");
        return -1;
    }

    // 获取格式，看是否设置成功
    bzero(&fmt, sizeof(fmt));
    fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    ret = ioctl(camfd, VIDIOC_G_FMT, &fmt);
    if (ret < 0)
    {
        perror("ioctl get fmt");
        return -1;
    }
    printf("pix width = %d, height = %d\n",
           fmt.fmt.pix.width, fmt.fmt.pix.height);

    // 5、申请缓存
    struct v4l2_requestbuffers req;
    req.count = 4; // 缓存数量
    req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    req.memory = V4L2_MEMORY_MMAP;

    if (ioctl(camfd, VIDIOC_REQBUFS, &req) < 0)
    {
        printf("申请缓存失败\n");
        return -1;
    }

    // 6、映射缓存
    // 映射，映射之前需要查询缓存信息->每个缓冲区逐个映射->将缓冲区放入队列
    struct v4l2_buffer mapbuffer;
    unsigned char *mmpaddr[4];                    // 用于存储映射后的首地址
    unsigned int addr_length[4];                  // 存储映射后空间的大小
    mapbuffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; // 初始化type
    for (int i = 0; i < 4; i++)
    {
        mapbuffer.index = i;
        ret = ioctl(camfd, VIDIOC_QUERYBUF, &mapbuffer); // 查询缓存信息
        if (ret < 0)
            perror("查询缓存队列失败");
        mmpaddr[i] = (unsigned char *)mmap(NULL, mapbuffer.length, PROT_READ | PROT_WRITE, MAP_SHARED, camfd, mapbuffer.m.offset); // mapbuffer.m.offset映射文件的偏移量
        addr_length[i] = mapbuffer.length;
        // 放入队列
        ret = ioctl(camfd, VIDIOC_QBUF, &mapbuffer);
        if (ret < 0)
            perror("放入队列失败");
    }

    // 7、打开设备
    int type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    ret = ioctl(camfd, VIDIOC_STREAMON, &type);
    if (ret < 0)
        perror("打开设备失败");

    // 8、从队列中提取一帧数据
    struct v4l2_buffer readbuffer;
    readbuffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    // ret = ioctl(camfd, VIDIOC_DQBUF, &readbuffer); // 从缓冲队列获取一帧数据（出队列）
    // bzero(&fmt, sizeof(readbuffer));
    // ret = ioctl(camfd, VIDIOC_DQBUF, &readbuffer); // 从缓冲队列获取一帧数据（出队列）
    // bzero(&fmt, sizeof(readbuffer));
    ret = ioctl(camfd, VIDIOC_DQBUF, &readbuffer); // 从缓冲队列获取一帧数据（出队列）
    // 出队列后得到缓存的索引index,得到对应缓存映射的地址mmpaddr[readbuffer.index]
    if (ret < 0)
        perror("获取数据失败");
    FILE *file = fopen("1.jpg", "w+"); // 建立文件用于保存一帧数据
    fwrite(mmpaddr[readbuffer.index], readbuffer.length, 1, file);
    fclose(file);

    // 9、读取数据后将缓冲区放入队列
    ret = ioctl(camfd, VIDIOC_QBUF, &readbuffer);
    if (ret < 0)
        perror("放入队列失败");

    // 10、关闭设备、取消映射
    ret = ioctl(camfd, VIDIOC_STREAMOFF, &type);
    if (ret < 0)
        perror("关闭设备失败");
    for (int i = 0; i < 4; i++)
        munmap(mmpaddr[i], addr_length[i]);

    close(camfd);
    return 0;
}
